﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.IO;
using System.Xml.Serialization;

namespace super_scrable.Models
{
    public class Player
    {
        public static string pathfile = @".\players.xml";

        private String pseudo;
        private List<Letter> letters;
        private Random r = new Random();

        public void addLetter(Letter letter)
        {
            letters.Add(letter);
        }

        public Letter getLetter(int i)
        {
            return letters[i];
        }

        public void setLetters(List<Letter> letters)
        {
            this.letters = letters;
        }

        public String Pseudo
        {
            get { return pseudo; }
            set { pseudo = value; }
        }
        private int points;

        public int Points
        {
            get { return points; }
            set { points = value; }
        }

        public Player() {}

        public Player(String pseudo, int points) : this()
        {
            this.pseudo = pseudo;
            this.points = points;
            this.letters = new List<Letter>();
        }

        public static List<Player> Load()
    	{
        	FileStream file = File.Open(pathfile, FileMode.Open);
            XmlSerializer serializer = new XmlSerializer(typeof(List<Player>));
            List<Player> players = (List<Player>)serializer.Deserialize(file);
        	file.Close();

            return players;
    	}

        public static void Save(List<Player> players)
        {
            FileStream file = File.Open(pathfile, FileMode.OpenOrCreate);
            XmlSerializer serializer = new XmlSerializer(typeof(List<Player>));
            serializer.Serialize(file, players);
            file.Close();
        }

        public int getNumberPiecesInHand()
        {
            return this.letters.Count;
        }

        public void generateMissingPiece()
        {
            int missing_piece = 7 - getNumberPiecesInHand();
            for (int i = 0; i < missing_piece; i++)
            {
                this.addLetter(new Letter(this.generateNewLetter()));
            }
        }

        public char generateNewLetter()
        {
            return (char)((r.Next(26) + 65));
        }
    }
}
